package com.example.hubeiweb.control;

import com.example.hubeiweb.service.UserService;
import com.example.hubeiweb.service.impl.UserServiceImpl;
import com.example.hubeiweb.vo.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login.action")
public class LoginController extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");//将请求格式改一下，不然传递的信息是乱码
        //获取前端传递过来的参数
        String username = request.getParameter("username").trim();
        String password = request.getParameter("password").trim();

        //建立服务层对象，完成相应的业务逻辑处理
        UserService userService = UserService.getInstance();
        Users users = new Users(username, password);
        Users result = userService.userLogin(users);

        //根据业务逻辑处理之后的结果，进入不同页面
        if (result != null) {
            //借助session会话对象
            HttpSession session = request.getSession();
            session.setAttribute("userInfo", result);
            response.sendRedirect("./main.jsp");
        } else {
            request.setAttribute("loginErr", "用户名或密码错误");
            request.getRequestDispatcher("./login.jsp").forward(request, response);
        }
    }
}